<template>
  <div style="padding: 30px">
    <div class="function-lan" style="width: 100%">
      <label for="cityList" style="margin-right: 10px">小区名称:</label>
      <div class="search-for">
        <el-input
          class="search-for-ipt"
          clearable
          @clear="getCityData"
          prefix-icon="el-icon-search"
          v-model="search"
          placeholder="请输入名称进行搜索"
        ></el-input>
      </div>
      <!-- 搜索按钮 -->
      <div class="search-btn" @click="searchFor">
        <Buttons :text="text1"></Buttons>
      </div>
      <!-- 筛选 -->
      <!-- <el-select
        v-model="value"
        filterable
        clearable
        :filter-method="pickData"
        placeholder="请选择负责人"
        class="pick"
      >
        <el-option
          v-for="item in worker"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
        </el-option>
      </el-select> -->
      <!-- 筛选按钮 -->
      <!-- <div class="search-btn" @click="pickData">
        <Buttons :text="text3"></Buttons>
      </div> -->
      <div class="add-new-manager">
        <!-- 添加按钮 -->
        <div class="add-manager-btn" @click="addCityDialog">
          <Buttons :text="text2"></Buttons>
        </div>
      </div>
    </div>
    <!-- table区域 -->
    <el-table
      :data="cityList"
      style="margin-top: 40px"
      v-loading="listLoading"
      border
      stripe
      fit
      highlight-current-row
      :default-sort="{ prop: 'order_number', order: 'descending' }"
    >
      <el-table-column
        label="排序编号"
        width="100px"
        prop="order_number"
        sortable
      ></el-table-column>
      <el-table-column
        label="社区编号"
        prop="id"
        width="80px"
      ></el-table-column>
      <el-table-column label="社区名称" prop="name"></el-table-column>
      <el-table-column label="负责人" prop="nickName" width="120px">
        <template slot-scope="scope">
          {{ scope.row.nickName | format }}
        </template>
      </el-table-column>
      <el-table-column
        :formatter="dateFormat"
        label="创建时间"
        width="180px"
        align="center"
        prop="create_time"
      >
      </el-table-column>
      <el-table-column label="操作" width="250px">
        <template slot-scope="scope">
          <!-- 添加权限 -->
          <el-tooltip
            class="item"
            effect="dark"
            content="编辑"
            placement="bottom-start"
          >
            <el-button
              type="success"
              icon="el-icon-edit"
              size="mini"
              @click="editCityInfo(scope.row.id)"
            ></el-button>
          </el-tooltip>
          <!-- 查看详情 -->
          <el-tooltip
            class="item"
            effect="dark"
            content="查看详情"
            placement="bottom-start"
          >
            <el-button
              type="primary"
              icon="el-icon-s-promotion"
              size="mini"
              @click="checkCityInfo(scope.row.id)"
            ></el-button>
          </el-tooltip>
          <!-- 分配负责人 -->
          <el-tooltip
            class="item"
            effect="dark"
            content="分配负责人"
            placement="bottom-start"
          >
            <el-button
              type="success"
              icon="el-icon-user"
              size="mini"
              @click="changePersonById(scope.row.id)"
            ></el-button>
          </el-tooltip>
          <!-- 删除按钮 -->
          <el-tooltip
            class="item"
            effect="dark"
            content="删除"
            placement="bottom"
          >
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeCityById(scope.row.id)"
            ></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <Pagination
      v-show="total > 0"
      :total="total"
      :page.sync="query.page_number"
      :limit.sync="query.page_size"
      @pagination="getCityData"
    />
    <!-- 创建小区对话框 -->
    <el-dialog
      title="创建小区"
      :visible.sync="createDialogVisible"
      width="50%"
      @close="createDialogClosed"
    >
      <el-form
        :model="createForm"
        :rules="createFormRules"
        ref="createFormRef"
        label-width="100px"
      >
        <el-form-item label="小区名称" prop="name">
          <el-input
            v-model="createForm.name"
            placeholder="请输入小区名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="排序编号(选填)" label-width="120px">
          <el-input
            v-model="createForm.order_number"
            placeholder="请输入排序编号"
          ></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="createDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="toCreateCity">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 更新小区信息对话框 -->
    <el-dialog
      title="更新小区信息"
      :visible.sync="updateDialogVisible"
      width="50%"
      @close="updateDialogClosed"
    >
      <el-form
        :model="updateForm"
        :rules="updateFormRules"
        ref="updateFormRef"
        label-width="100px"
      >
        <el-form-item label="小区名称" prop="id">
          <el-input
            v-model="updateForm.id"
            placeholder="请输入地区id"
          ></el-input>
        </el-form-item>
        <el-form-item label="小区名称" prop="name">
          <el-input
            v-model="updateForm.name"
            placeholder="请输入小区名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="排序编号" label-width="120px">
          <el-input
            v-model="updateForm.order_number"
            placeholder="请输入排序编号"
          ></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="updateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="toupdateCity">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 查看小区详情 -->
    <el-dialog
      title="查看小区详情"
      :visible.sync="checkDialogVisible"
      width="50%"
    >
      <el-descriptions title="小区信息" :column="1">
        <el-descriptions-item label="id">{{
          checkForm.id
        }}</el-descriptions-item>
        <el-descriptions-item label="小区名称">{{
          checkForm.name
        }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{
          checkForm.create_time | dateFormat
        }}</el-descriptions-item>
        <el-descriptions-item label="编号">{{
          checkForm.order_number
        }}</el-descriptions-item>
      </el-descriptions>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="checkDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="changePerson">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="分配负责人"
      :visible.sync="changeDialogVisible"
      width="50%"
      @close="changeDialogClosed"
    >
      <label for="workerList" style="margin-right: 20px"
        >请选择你要分配的负责人:</label
      >
      <el-select
        v-model="user_id"
        clearable
        placeholder="请选择负责人"
        class="pick"
      >
        <el-option
          v-for="item in workerList"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
        </el-option>
      </el-select>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelAssignment">清除分配信息</el-button>
        <el-button @click="changeDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="changePerson">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {
  getCityList,
  checkCityInfo,
  updateInfo,
  removeCity,
  createCity,
  getDataTotal,
  getPerson,
  updatePerson
} from "@/api/community";
import Buttons from "@/components/button/index.vue";
import Pagination from "@/components/Pagination";
import { createFormRules, updateFormRules } from "@/config/community/index";
import moment from "moment";
import { checkPermission } from "@/utils/hasPermission";
// import { searchInfo } from "@/utils/search";
export default {
  name: "city",
  components: {
    Buttons,
    Pagination
  },
  filters: {
    dateFormat: function(date) {
      return moment.unix(date).format("YYYY-MM-DD HH:mm:ss");
    },
    format: function(data) {
      if (data === null) {
        return "未分配";
      }
      return data;
    }
  },
  data() {
    return {
      query: {
        page_number: 1,
        page_size: 20
      },
      total: 0,
      text1: "搜索",
      text2: "创建",
      // text3: "筛选",
      text4: "取消分配",
      search: "",
      listLoading: false,
      cityList: [],
      createDialogVisible: false,
      createForm: {
        name: "",
        order_number: 1
      },
      createFormRules: {},
      updateDialogVisible: false,
      updateForm: {
        name: "",
        order_number: 1
      },
      updateFormRules: {},
      checkDialogVisible: false,
      checkForm: {},
      // value: "",
      // worker: [],
      workerList: [],
      changeDialogVisible: false,
      user_id: "",
      city_id: 0
    };
  },
  watch: {
    "createForm.name"(val) {
      console.log(val);
    }
  },
  created() {
    this.createFormRules = createFormRules;
    this.updateFormRules = updateFormRules;
    this.getCityData();
  },
  methods: {
    checkPermission,
    async getCityData() {
      let self = this;
      self.listLoading = true;
      const res = await getCityList(self.query);
      self.cityList = res.result;
      console.log(this.cityList);
      const data = await getDataTotal();
      // console.log(data)
      // 筛选项
      // this.cityList.map(item => {
      //   if (item.nickName === null) {
      //     this.worker.push({ value: "未分配", label: "未分配" });
      //   } else {
      //     this.worker.push({
      //       value: item.nickName,
      //       label: item.nickName
      //     });
      //   }
      // });
      // const result = new Map();
      // this.worker = this.worker.filter(arr => {
      //   return !result.has(arr.value) && result.set(arr.label, 1);
      // });
      // 筛选项结束
      // console.log(this.worker);
      setTimeout(() => {
        self.listLoading = false;
      }, 1.5 * 1000);
      self.total = data.result[0].numbers;
    },
    searchFor() {
      let self = this;
      self.listLoading = true;
      let reg = new RegExp(self.search.trim(), "i");
      let resArr = [];
      self.cityList.filter(item => {
        for (let i in item) {
          // console.log(item[i]);
          if (reg.test(item[i])) {
            resArr.push(item);
          }
        }
      });
      // 去重
      const res = new Map();
      setTimeout(() => {
        this.cityList = resArr.filter(arr => {
          return !res.has(arr.id) && res.set(arr.id, 1);
        });
        self.total = this.cityList.length;
        self.listLoading = false;
      }, 1.5 * 500);
    },
    addCityDialog() {
      if (!this.checkPermission()) return;
      this.createDialogVisible = true;
    },
    editCityInfo(id) {
      if (!this.checkPermission()) return;
      let self = this;
      self.updateDialogVisible = true;
      self.updateForm.id = id;
      //   console.log(self.updateForm);
    },
    async checkCityInfo(id) {
      if (!this.checkPermission()) return;
      let self = this;
      self.checkDialogVisible = true;
      const res = await checkCityInfo(id);
      console.log(res);
      self.checkForm = res.result[0];
    },
    async removeCityById(id) {
      if (!this.checkPermission()) return;
      //   console.log(id);
      let self = this;
      const confirmResult = await self
        .$confirm("此操作将永久删除该社区, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
        .catch(err => err);
      if (confirmResult !== "confirm") {
        return self.$message.info("已经取消删除");
      }
      const res = await removeCity(id);
      if (res.code !== 1) {
        return self.$message.error("删除失败！");
      }

      self.$message.success("删除成功！");
      self.getCityData();
    },
    // 时间格式化
    dateFormat(row, column) {
      // dateFormat();
      // console.log(row, column);
      var date = row[column.property];
      if (date == undefined) return "";
      return this.$moment.unix(date).format("YYYY-MM-DD HH:mm:ss");
    },
    createDialogClosed() {
      console.log(1);
      this.$refs.createFormRef.resetFields();
    },
    toCreateCity() {
      let self = this;
      self.$refs.createFormRef.validate(async valid => {
        if (!valid) return;
        const res = await createCity(self.createForm);
        if (res.code !== 1) {
          self.$message.error("创建失败！");
        } else {
          self.$message.success("创建成功！");
        }
        self.createDialogVisible = false;
        self.getCityData();
      });
    },
    updateDialogClosed() {
      this.$refs.updateFormRef.resetFields();
    },
    toupdateCity() {
      let self = this;
      self.$refs.updateFormRef.validate(async valid => {
        if (!valid) return;
        const res = await updateInfo(self.updateForm);
        console.log(res);
        if (res.code !== 1) {
          self.$message.error("更新失败！");
        } else {
          self.$message.success("更新成功！");
        }
        self.updateDialogVisible = false;
        self.getCityData();
      });
    },
    // pickData() {
    //   let self = this
    //   console,log()
    //   searchInfo(self.value,self.cityList)
    // }
    async changePersonById(id) {
      this.changeDialogVisible = true;
      const res = await getPerson();
      console.log(res.result);
      res.result.map(item => {
        this.workerList.push({ label: item.nickName, value: item.id });
      });
      console.log(this.workerList);
      this.city_id = id;
    },
    async changePerson() {
      // console.log(id);
      const res = await updatePerson({
        user_id: this.user_id,
        city_id: this.city_id
      });
      console.log(res);
      if (res.code != 1) return this.$message.error("分配负责人失败!");
      this.$message.success("分配负责人成功!");
      this.changeDialogVisible = false;
      this.getCityData();
    },
    async cancelAssignment() {
      const res = await updatePerson({
        user_id: "0",
        city_id: this.city_id
      });
      console.log(res);
      if (res.code != 1) return this.$message.error("分配负责人失败!");
      this.$message.success("分配负责人成功!");
      this.changeDialogVisible = false;
      this.getCityData();
    },
    changeDialogClosed() {
      this.city_id = 0;
      this.user_id = "";
      this.workerList = [];
    }
  }
};
</script>
<style lang="scss" scoped></style>
